package com.njlime.sys.service;

import com.njlime.core.exception.BusinessException;
import com.njlime.core.helper.GlobalValue;
import com.njlime.core.helper.PageBean;
import com.njlime.core.utils.StringUtil;
import com.njlime.core.web.validation.annotation.support.ValidateService;
import com.njlime.sys.entities.Unit;
import com.njlime.sys.entities.UnitWxConfig;
import com.njlime.sys.entities.User;
import com.njlime.sys.repository.UserDao;
import com.njlime.sys.security.util.UserUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.security.utils.Digests;
import org.springside.modules.utils.Encodes;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by Dean on 2017-7-19.
 */
@Service
public class UserService {
    public static final String HASH_ALGORITHM = "SHA-1";
    public static final int HASH_INTERATIONS = 1024;
    public static final int SALT_SIZE = 8;

    @Resource
    private UserDao userDao;
    @Resource
    private UnitService unitService;
    @Resource
    private RoleService roleService;


    /**
     * 根据登录名获取用户
     *
     * @param login_name
     * @return
     */
    public User getUserByLoginName(String login_name) {
        return UserUtils.getByLoginName(login_name);
    }

    /**
     * 更新用户登录IP及登录时间
     *
     * @param user
     */
    @Transactional(readOnly = false)
    public void updateUserLoginInfo(User user) {
        // 更新本次登录信息
        User newUser = new User();
        newUser.setId(user.getId());
        newUser.setLogin_ip(user.getLogin_ip());
        newUser.setLogin_time(new Date());
        newUser.setUpdate_time(user.getUpdate_time());
        newUser.setUpdater(user.getUpdater());
        userDao.updateUser(newUser);
    }

    /**
     * 根据ID获取用户
     *
     * @param id
     * @return
     */
    public Map<String,Object> getById(Integer id) {
        Map<String,Object> user = userDao.getUserMap(id);
        user.put("unit",unitService.findOne(Integer.valueOf(user.get("unit_id").toString())));
        return user;
    }

    /**
     * 根据openid获取用户
     * @param openid
     * @return
     */
    public User getByOpenid(String openid){
        return userDao.getByOpenid(openid);
    }

    /**
     * 根据手机号获取用户
     * @param mobile
     * @return
     */
    public User getByMobile(String mobile, boolean available) {
        return userDao.getByMobile(mobile, available);
    }

    /**
     * 获取用户列表
     *
     * @param pageBean
     * @param user
     * @return
     */
    public PageBean list(PageBean pageBean, User user) {
        return userDao.list(pageBean, user);
    }

    /**
     * 添加用户
     *
     * @param user
     */
    @Transactional(readOnly = false)
    public User addUser(User user, Integer role_id) {
        User ori = getUserByLoginName(user.getLogin_name());
        if (ori != null) {
            throw new BusinessException("登录名已存在");
        }
        ori = null;
        ori = getByMobile(user.getMobile(),false);
        if (ori != null) {
            throw new BusinessException("手机号已存在");
        }
        user.setLogin_flag(GlobalValue.YES);
        user.setCreate_time(new Date());
        user.setIs_del(GlobalValue.NO);
        user.setPassword(entryptPassword(user.getPassword()));
        user = userDao.save(user);
        //用户角色
        roleService.insertUserRole(role_id, user.getId());
        return user;
    }

    /**
     * 编辑用户
     *
     * @param user
     */
    @Transactional(readOnly = false)
    public int editUser(User user, Integer role_id) {
        if(StringUtil.isEmpty(user.getLogin_name())){
            User ori = getUserByLoginName(user.getLogin_name());
            if (ori != null && ori.getId() != user.getId()) {
                throw new BusinessException("登录名已存在");
            }
        }
        if(!StringUtil.isEmpty(user.getMobile()) && !StringUtil.isMobile(user.getMobile())){
            throw new BusinessException("手机号格式错误");
        }
        // 如果新密码为空，则不更换密码
        if (StringUtil.isNotBlank(user.getPassword())) {
            user.setPassword(entryptPassword(user.getPassword()));
        }
        // 清除用户缓存
        UserUtils.clearCache(user);
        user.setUpdater(UserUtils.getUser().getId());
        user.setUpdate_time(new Date());
        //userDao.update(user);
        int num = userDao.updateUser(user);
        //更新用户角色
        if(role_id != null) {
            roleService.updateUserRole(role_id, user.getId());
        }
        return num;
    }

    /**
     * 删除用户
     * @param idArray
     */
    @Transactional(readOnly = false)
    public void deleteUser(String[] idArray) {
        User user = UserUtils.getUser();
        if (idArray != null && idArray.length > 0){
            for (String idStr : idArray) {
                Integer id = Integer.parseInt(idStr);
                if (id.equals(user.getId())) {
                    throw new BusinessException("不能删除当前用户");
                }
                UserUtils.clearCache(UserUtils.get(id + ""));
                userDao.deleteUser(id);
            }
        }
    }

    /**
     * 根据角色id获取用户列表
     * @param role_id
     * @return
     */
    public List<Map<String,Object>> getUserByRole(Integer role_id){
        return userDao.getUserByRole(role_id);
    }


    /**
     * 用户注册
     * @param unit
     * @param user
     */
    @Transactional
    public void register(Unit unit, User user) {
        try{
            //创建单位
            unit.setParent_id(GlobalValue.SYS_UNIT_ID);
            unit.setStatus(GlobalValue.UNAUDIT);
            ValidateService.valid(unit);
            unit.setCreator(GlobalValue.SYS_USER_ID);
            unit = unitService.addUnit(unit);
            //创建用户
            user.setUnit_id(unit.getId());
            user.setStatus(GlobalValue.AUDITED);
            ValidateService.valid(user);
            user.setCreator(GlobalValue.SYS_USER_ID);
            user = addUser(user, GlobalValue.DEFAULT_ROLE_ID);
            //更新运营者
            unit.setManager_id(user.getId());
            unitService.editUnit(unit);
        }catch (Exception e){
            throw new BusinessException(e.getMessage());
        }
    }

    /**
     * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
     */
    private String entryptPassword(String pwd) {
        String plain = Encodes.unescapeHtml(pwd);
        byte[] salt = Digests.generateSalt(SALT_SIZE);
        byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
        return Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword);
    }

}
